package com.banciyuan.bcywebview.biz.search;

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoreApi;
import com.banciyuan.bcywebview.base.fragment.BasePullLoadFragment;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;

import com.banciyuan.bcywebview.utils.http.BcyPair;

import org.json.JSONArray;
import org.json.JSONObject;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by squall on 2015/9/7.
 */
public class SearchAutoFragment extends BasePullLoadFragment {

    private SearchAutoAdapter mAdapter;
    private RequestQueue queue;
    private String query;
    private List<String> slist = new ArrayList<>();
    private ListView mList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.search_auto_list, null);
        initArgs();
        initUi(view);
        initAction();
        return view;
    }

    @Override
    protected void initUi(View rootview) {
        mList = (ListView) rootview.findViewById(R.id.search_auto_lv);
    }

    @Override
    protected void initAction() {
        mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                SearchActivity searchActivity = (SearchActivity) getActivity();
                if (i == slist.size() - 2) {
                    searchActivity.showResultFragment(slist.get(i), 7);
                } else if (i == slist.size() - 1) {
                    searchActivity.showResultFragment(slist.get(i), 6);
                } else {
                    searchActivity.showResultFragment(slist.get(i), 0);
                }
                searchActivity.hideSoftKeyboard();
            }
        });
    }

    @Override
    protected void initData() {
        findServerTitle();
    }

    public void findServerTitle() {
        final String url = HttpUtils.BASE_URL + CoreApi.getGetcorelist();
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.SEARCH_QUERY, query));
        paramsList.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        final HashMap<String, String> map = HttpUtils.getData(paramsList);

        new AsyncTask<String, String, String>() {
            @Override
            protected String doInBackground(String... strings) {
                String temp = strings[0];
                for (Map.Entry<String, String> entry : map.entrySet())
                    temp += entry.getKey() + "=" + entry.getValue();
                if (queue.getCache().get(temp) != null) {
                    return new String(queue.getCache().get(temp).data, Charset.defaultCharset());
                } else {
                    return "net";
                }
            }

            @Override
            protected void onPostExecute(String s) {
                if (s.equals("net")) {
                    Response.Listener<String> onSucc = new Response.Listener<String>() {
                        @Override
                        public void onResponse(String o) {
                            dealJson(o);
                        }
                    };
                    Response.ErrorListener onError = new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            dealJson("");
                        }
                    };

                    OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
                    StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
                    queue.add(stringRequestParam);

                } else {
                    dealJson(s);
                }
            }
        }.execute(url);
    }

    private void dealJson(String s) {

        if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                slist.clear();
                for (int i = 0; i < jsonArray.length(); i++) {
                    slist.add(jsonArray.getString(i));
                }
                slist.add(query);
                slist.add(query);
                if (mAdapter == null) {
                    mAdapter = new SearchAutoAdapter(slist, getActivity(), query);
                    mList.setAdapter(mAdapter);
                } else {
                    mAdapter.setOrign(query);
                    mAdapter.notifyDataSetChanged();
                }
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {

    }

    @Override
    public void setArguments(Bundle args) {
        queue = VolleyQueue.getRquest(getActivity());
        query = args.getString("query");
        if (!TextUtils.isEmpty(query)) {
            initData();
        } else {
            slist.clear();
            if (mAdapter != null) {
                mAdapter.notifyDataSetChanged();
            }
        }

    }
}
